package com.dianqu.weather.web.engine;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dianqu.weather.core.common.ClassUtils;
import com.dianqu.weather.core.model.WeatherInfo;

@Service
public class ContextStrategy {

	private final Logger logger = Logger.getLogger(getClass());
	List<EngineStrategy> strategies = new ArrayList<EngineStrategy>();

	public WeatherInfo dosearch(String location) {
		for (EngineStrategy strategy : strategies) {
			WeatherInfo info = strategy.getInfo(location);
			if (info != null) {
				return info;
			}
		}
		logger.info("Searching the weather of " + location + " failed ");
		return null;
	}

	@Value("com.dianqu.weather.web.engine.strategy")
	public void setPackagesToScan(String packagesToScan) {
		if (packagesToScan != null) {
			List<Object> objects = ClassUtils.getObjects(packagesToScan);
			strategies.addAll((Collection<? extends EngineStrategy>) objects);
			Collections.sort(strategies, new Comparator<EngineStrategy>() {
				public int compare(EngineStrategy o1, EngineStrategy o2) {
					return o2.getPriority() - o1.getPriority();
				}
			});
		}
	}

}
